// pages/index/index.js
Page({
  data: {
    reports: [],
    loading: true,
    userId: '' // 存储当前用户ID
  },

  onLoad: function() {
    this.getUserId(); // 页面加载时获取用户ID
  },

  getUserId: function() {
    const userId = wx.getStorageSync('userId');
    console.log('获取到的用户ID:', userId); // 调试日志
    if (userId) {
      this.setData({ userId: userId });
      this.generateReport(userId); // 加载当前用户的访问报告
    } else {
      wx.showToast({
        title: '未能获取用户ID',
        icon: 'none'
      });
    }
  },

  generateReport: function(userId) {
    let that = this;
    const db = wx.cloud.database();
    db.collection('photos').where({
      userId: userId
    }).get().then(res => {
      if (res.data && res.data.length > 0) {
        const reports = that.processLocations(res.data);
        that.setData({
          reports: reports,
          loading: false
        });
      } else {
        that.setData({ loading: false, reports: 'No data found' });
      }
    }).catch(err => {
      console.error('获取访问报告失败', err);
      that.setData({ loading: false });
    });
  },

  processLocations: function(photos) {
    let report = {};
    photos.forEach(photo => {
      const location = photo.location; // 假设 location 是 { latitude: ..., longitude: ... }
      if (report[location.city]) {
        report[location.city].count += 1;
      } else {
        report[location.city] = {
          city: location.city,
          count: 1,
          latitude: location.latitude, // 直接使用 location.latitude
          longitude: location.longitude, // 直接使用 location.longitude
        };
      }
    });
    return Object.values(report);
  },

  uploadPhoto: function() {
    let that = this;
    wx.chooseImage({
      success: function(res) {
        const filePath = res.tempFilePaths[0];
        const cloudPath = `photos/${Date.now()}-${Math.floor(Math.random() * 1000)}${filePath.match(/\.[^.]+?$/)[0]}`;
        wx.cloud.uploadFile({
          cloudPath: cloudPath,
          filePath: filePath,
          success: uploadRes => {
            const fileID = uploadRes.fileID;
            console.log('上传文件成功，文件ID:', fileID); // 输出调试信息
            wx.getLocation({
              type: 'wgs84', // 使用 wgs84 坐标系
              success(res) {
                const latitude = res.latitude;
                const longitude = res.longitude;
                console.log('获取到的纬度：', latitude); // 添加日志输出
                console.log('获取到的经度：', longitude); // 添加日志输出
                console.log('获取地理位置成功，纬度:', latitude, '经度:', longitude); // 输出调试信息
  
                // 调用腾讯地图API获取城市信息
                that.getCityInfo(latitude, longitude, fileID);
              },
              fail(err) {
                console.error('获取地理位置失败:', err);
                wx.showToast({
                  title: '获取地理位置失败',
                  icon: 'none',
                  duration: 2000
                });
              },
            });
          },
          fail: function(uploadErr) {
            console.error('上传照片到云存储失败:', uploadErr);
            wx.showToast({
              title: '上传失败',
              icon: 'none',
              duration: 2000
            });
          },
        });
      },
      fail: function(chooseErr) {
        console.error('选择图片失败:', chooseErr);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  
  getCityInfo: function(latitude, longitude, fileID) {
    let that = this;
    // 假设使用的是腾讯地图API
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/', // 腾讯地图逆地理编码API
      data: {
        location: `${latitude},${longitude}`,
        key: '5YRBZ-EOXKU-IUHVQ-GNISD-YBH22-Z2FVJ' // 替换为您的腾讯地图API密钥
      },
      success(res) {
        if (res.data.status === 0 && res.data.result) {
          const city = res.data.result.address_component.city;
          console.log('获取到的城市信息：', city);
          that.addPhotoToDatabase(fileID, latitude, longitude, city);
        } else {
          console.error('腾讯地图API调用失败:', res.data.status);
          wx.showToast({
            title: '获取城市信息失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(err) {
        console.error('请求腾讯地图API失败:', err);
        wx.showToast({
          title: '请求城市信息失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
  
  addPhotoToDatabase: function(fileID, latitude, longitude, city) {
    let that = this;
    const db = wx.cloud.database();
    const userId = this.data.userId; // 获取当前用户ID
    db.collection('photos').add({
      data: {
        fileID: fileID,
        userId: userId, // 存储当前用户ID
        location: {
          latitude: latitude,
          longitude: longitude,
          city: city // 添加城市信息
        },
        uploadTime: new Date(),
        description: '描述信息',
        public: true,
        tags: ['标签1', '标签2']
      },
      success: function() {
        console.log('图片添加到数据库成功');
        wx.showToast({
          title: '图片保存成功',
          icon: 'success',
          duration: 2000
        });
        // 刷新页面数据
        that.generateReport(userId);
      },
      fail: function(e) {
        console.error('图片添加到数据库失败', e);
        wx.showToast({
          title: '图片保存失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },
});
